import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path:"/",
    // 重定向
    redirect:"/login"
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    redirect:"/home/hi",
    // 子路由
    children:[
      {
        // 子路由不能加/
        path:"hi",
        name:"hi",
         component: () => import( '../components/HelloWorld.vue')
      },
      {
        // 子路由不能加/
        path:"index",
        name:"index",
         component: () => import( '../views/dashboard.vue')
      },
      {
        // 子路由不能加/
        path:"list",
        name:"list",
         component: () => import( '../components/list.vue')
      },
       {
        // 子路由不能加/
        path:"protect",
        name:"protect",
         component: () => import( '../components/protect.vue')
      },
    ]   
  },
  {
    path: '/about',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

//重写push方法


// 路由守卫拒绝跳转 重写push方法
// const org = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location) {
// return org.call(this, location).catch(err => err)
// }

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 动态路由
let obj ={
  path:'/login',
  name:'login',
  component: () => import('../views/login.vue')
}
router.addRoute(obj)


// 全局路由守卫
router.beforeEach((to,from,next) => {
  let token = localStorage.getItem("token")
  // 如果登录 放行
  if(to.path == "/login"){
    return next()
  }else if (!token){
    // 没有token 送去登录
    return next('/login')
  }else{
    const hasName = store.state.name
    if(hasName){
      // 有token 放行
    next()
    }else{
      store.dispatch("getUserInfo")
      next()
    }
    
  }
})
export default router
